/**
 *
 * @author Ryan Thomas <s548169@sbuniv.edu>
 */

package MultiUserChatServer;


public class ThreadLinkedList {
    
    private LinkedListNode start;
    private LinkedListNode end;
    private int length;
    
    public ThreadLinkedList(){
        start = null;
        length = 0;
    }
    /**
     * 
     * @param input the Thread being added to the linked list
     */
    public void addThread(ClientThread input){
        if(start == null){
            start = new LinkedListNode(input);
            end = start;
        }
        else{
            end.setNext(new LinkedListNode(input));
            end = end.getNext();
        }
        length++;
    }
    /**
     * 
     * @param threadID the Thread to be removed
     */
    public void removeThread(long threadID){
       if(start != null){
            Thread startThread = start.getData();
            if(threadID == startThread.getId()){
                start = start.getNext();
                length--;
            }
            else{
                LinkedListNode previous = start;
                LinkedListNode current = start.getNext();
                while(current!=null){
                    Thread temp = current.getData();
                    if(temp.getId() == threadID){
                        previous.setNext(current.getNext());
                        length--;
                    }
                    previous = current;
                    current = current.getNext();
                }
            }
       }
    }
    /**
     * 
     * @param message The message that is being sent
     * @param from The Thread id that message is coming from
     */
    public void send(String message, long from){
        LinkedListNode current = start;
        while(current != null){
            ClientThread temp = (ClientThread) current.getData();
            if(temp.getId()!=from){
                temp.send(message);
            }
            current = current.getNext();
        }
    }
    /**
     * 
     * @return a long[] containing the IDs of all the running threads
     */
    public long[] getThreadIDs(){
        LinkedListNode current = start;
        long[] threadIDs = new long[length];
        int counter = 0;
        while(current!= null){
            ClientThread temp = current.getData();
            threadIDs[counter] = temp.getId();
            current = current.getNext();
            counter++;
        }
        return threadIDs;
    }
    /**
     * 
     */
    public void killAllSockets(){
        LinkedListNode current = start;
        while(current!= null){
            ClientThread temp = current.getData();
            temp.send("SVR:SEND:TERM\n");
            temp.killSocket();
            current = current.getNext();
        }
    }
}
